import React, {useState, useReducer, useMemo, useCallback, memo} from 'react'
const reducer = (state, action) => {
  switch(action.type) {
    case 'ADD':
      return state + 1
    default:
      return state
  }
}

function OtherHook () {
  const [text, setText] = useState('input')
  const [count, dispatchCount] = useReducer(reducer, 0)

  const config = useMemo(() => ({
    text: count,
    fontSize: count + 12
  }), [count])

  const handleClick = useMemo(() => () => {
    dispatchCount({type: 'ADD'})
  }, [])

  // const handleClick = useCallback(() => {
  //   dispatchCount({type: 'ADD'})
  // }, [])

  return <>
    <input onChange={(e) => setText(e.target.value)} />
    <br />
    <MemoChild config={config} callback={handleClick} />
  </>
}

function Child ({config, callback}) {
  // Child 如果不用memo包裹，外层使用useMemo，也依然会重复渲染。 使用memo相当于给组件添加了shouldComponentUpdate方法
  console.log('re-render')

  return <button style={{fontSize: config.fontSize}} onClick={callback}>{config.text}</button>
}

const MemoChild = memo(Child, 
  // function areEqual(prevProps, nextProps) {
  //   console.log(prevProps, nextProps)
  // }
)

export default OtherHook